package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Admin;
import com.ywgt.pojo.Role;
import com.ywgt.service.PermissionService;
import com.ywgt.service.RoleService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@CrossOrigin
@RestController
@RequestMapping("/admin/role")
@ApiModel("角色管理")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    PermissionService permissionService;

    /**
     *  page: 1,
     *         limit: 20,
     *         name: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getRoles(String name, @RequestParam(required = false,defaultValue = "add_time") String sort,
                           @RequestParam(required = false,defaultValue = "desc") String order,
                           @RequestParam(required = false,defaultValue = "1") int page,
                           @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Role> roles=roleService.getRoles(name,page,limit,sort,order);
        List<Role> items = roles.getResult();
        long total = roles.getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/options")
    public Object getAll(){
        List<Role> roles = roleService.list();
        List<Map<String, Object>> data = new ArrayList<>();
        for (Role role : roles) {
            Map<String, Object> option = new HashMap<>(2);
            option.put("value", role.getId());
            option.put("label", role.getName());
            data.add(option);
        }
        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@RequestBody Role role){
        if(roleService.save(role)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Role role){
        if(roleService.removeById(role)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }

    @PostMapping("/update")
    public Object update(@RequestBody Role role){
        if(roleService.updateById(role)){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
    @GetMapping("/permissions")
    public Object permissions(Integer id){
        return null;
    }

}
